package com.yitao.cms.service.product;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.product.ProductShareCopywritingDto;
import com.yitao.client.model.product.ProductShareCopywritingModel;
import com.yitao.client.model.product.QProductShareCopywritingModel;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Date: 2019/12/11 11:38
 * @Author: Kien
 */
@Service
public class ProductShareCopywritingService extends GenericEntityService<ProductShareCopywritingModel, ProductShareCopywritingDto, QProductShareCopywritingModel> {

    public ProductShareCopywritingService(EntityManager entityManager) {
        super(entityManager);
    }

    /**
     * 功能描述: 新增分享描述
     *
     * @param shareDescribe 描述内容
     *
     * @param request
     * @return
     * @auther Kien
     * @date 2019/12/11 11:41
     *
     */
    @Transactional
    public DataOutput<ProductShareCopywritingDto> saveProductShare(String shareDescribe, HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            logger.info("用户未登录");
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        if(StringUtils.isBlank(shareDescribe)) {
            logger.info("文案内容不能为空");
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "新增文案内容不能为空");
        }
        if(shareDescribe.trim().length() > 10) {
            logger.info("文案内容长度不能大于10个字");
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "文案内容长度不能大于10个字");
        }
        ProductShareCopywritingModel productShareCopywritingModel = new ProductShareCopywritingModel();
        productShareCopywritingModel.setShopId(userSession.getShopId());
        productShareCopywritingModel.setDeleteState(false);
        productShareCopywritingModel.setShareDescribe(shareDescribe); // 分享描述
        productShareCopywritingModel.setCreateBy(userSession.getId());
        Date date = new Date();
        productShareCopywritingModel.setCreateTime(date);
        productShareCopywritingModel.setLastUpdateTime(date); // 新增时，最后修改时间就是新增时间
        ProductShareCopywritingModel save = repository.save(productShareCopywritingModel);
        return new DataOutput(convertEntityToDto(save));
    }

    /**
     * 功能描述: 修改分享描述
     *
     * @param shareDescribe 描述内容
     *
     * @param request
     * @return
     * @auther Kien
     * @date 2019/12/11 11:41
     *
     */
    @Transactional
    public DataOutput updateProductShare(Long id, String shareDescribe, HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            logger.info("用户未登录");
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        if(id == null) {
            logger.info("需要修改id不能为空");
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "修改文案内容id不能为空");
        }
        if(StringUtils.isBlank(shareDescribe)) {
            logger.info("文案内容不能为空");
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "修改文案内容不能为空");
        }
        if(shareDescribe.trim().length() > 10) {
            logger.info("文案内容长度不能大于10个字");
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "文案内容长度不能大于10个字");
        }
        int i = repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.id.eq(id)).get(), it -> it.set(Q.shareDescribe, shareDescribe));
        if(i == 0) {
            logger.info("修改文案失败");
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "修改文案失败");
        }
        return new DataOutput();
    }

    /**
     * 功能描述: 删除分享文案
     *
     * @param id id
     * @param request
     *
     * @return 
     * @auther Kien
     * @date 2019/12/11 14:14
     */
    @Transactional
    public DataOutput delProductShare(Long id, HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            logger.info("用户未登录");
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        if(id == null) {
            logger.info("需要删除id不能为空");
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "删除文案内容id不能为空");
        }
        int i = repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.id.eq(id)).get(), it -> it.set(Q.deleteState, true));
        if(i == 0) {
            logger.info("删除商品分享文案失败");
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "删除商品分享文案失败");
        }
        return new DataOutput();
    }

    /**
     * 功能描述: 查询分享文案
     *
     * @param shareDescribe
     * @param pageNo
     * @param pageSize
     *
     * @param request
     * @return
     * @auther Kien
     * @date 2019/12/11 14:22
     */
    public PagedOutput<ProductShareCopywritingDto> findProductShareList(String shareDescribe, Integer pageNo, Integer pageSize, HttpServletRequest request) {
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            logger.info("用户未登录");
            return new PagedOutput(CommonStatus.UNAUTHORIZED, pagedInput, 0, new ArrayList());
        }
        try {
            PagedOutput<ProductShareCopywritingModel> pagedOutput = repository.pagingList(PredicateBuilder.conjunction()
                    .and(() -> Q.deleteState.eq(false))
                    .and(() -> Q.shopId.eq(userSession.getShopId()))
                    .ifNotNullThenAnd(shareDescribe, () -> Q.shareDescribe.like("%" + shareDescribe + "%"))
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.lastUpdateTime));
            List<ProductShareCopywritingDto> list = new ArrayList<>();
            if(pagedOutput != null && pagedOutput.getData() != null) {
                list = pagedOutput.getData().stream().map(it ->{
                    ProductShareCopywritingDto productShareCopywritingDto = new ProductShareCopywritingDto();
                    BeanUtils.copyProperties(it, productShareCopywritingDto);
                    productShareCopywritingDto.setCreateTimeString(DateUtils.getDateSecondFormat(it.getCreateTime()));
                    return productShareCopywritingDto;
                }).collect(Collectors.toList());
            }
            return new PagedOutput(pagedInput, pagedOutput.getTotalElements(), list);
        } catch (Exception e) {
            logger.info("获取商品分享文案列表异常");
            return new PagedOutput(CommonStatus.SERVER_ERROR, pagedInput, 0, new ArrayList());
        }

    }
}
